package com.navi.loaddata.loadService.impl.opeHis;

import com.navi.loaddata.core.errorLog.ErrorCode;
import com.navi.loaddata.core.etlException.ETLException2;
import com.navi.loaddata.core.gpEntity.MOpeD;
import com.navi.loaddata.core.gpEntity.MProdD;
import com.navi.loaddata.core.gpEntity.hisToGP.*;
import com.navi.loaddata.core.mysqlEntity.EtlConfDModel;
import com.navi.loaddata.core.repository.impl.GreenPlumRepositoryImpl;
import com.navi.loaddata.core.util.JacksonUtil;
import com.navi.loaddata.core.util.LoggerUtil;
import com.navi.loaddata.core.util.ProcessUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class LoadOpeHisService {
    private static final Logger logger = LoggerFactory.getLogger(LoadOpeHisService.class);

    @Autowired
    private AmqpTemplate rabbitTemplate;
    @Autowired
    private LoadOpeHisInfoService loadOpeHisInfoService;


    public String[] loadprodHisDataMain(EtlConfDModel etlConfD) throws Exception {
        String[] resMsg = loadprodHis(etlConfD);
        String msg = etlConfD.getOpe();
        if (StringUtils.isEmpty(etlConfD.getOpe())) msg = "ALL";
        logger.info("OpeId={} loadOpeHis finish!", msg);
        return resMsg;


    }

    private String[] loadprodHis(EtlConfDModel etlConfD) throws Exception {
        String[] resMsg = new String[3];
        int okCnt = 0;
        int errCnt = 0;
        String errMsg = null;
//        long startTime = System.currentTimeMillis();
        List<ProductHis> productHisList = loadOpeHisInfoService.getTrackOutInfo(etlConfD);
        logger.info("HIS 表 TRACKOUT 数量：{}",productHisList.size());
//        long endTime = System.currentTimeMillis();
//        long time=endTime-startTime;
//        logger.warn("查询TrackOut的时间：{}",time);
        if (!productHisList.isEmpty()) {
//            startTime = System.currentTimeMillis();
            HashMap<String,ProductHis> shopStartTime=loadOpeHisInfoService.getShopStartTimestamp(productHisList);
//            endTime = System.currentTimeMillis();
//            time=endTime-startTime;
//            logger.warn("查询SHOPSTARTTIMESTAMP的时间：{}",time);
//            startTime = System.currentTimeMillis();
            HashMap<String, Integer> prodMap = loadOpeHisInfoService.getProdMap();
            HashMap<String, Integer> opeMap = loadOpeHisInfoService.getOpeMap();
//            endTime = System.currentTimeMillis();
//            time=endTime-startTime;
//            logger.warn("查询PROD,OPE的时间：{}",time);

            long startTime = System.currentTimeMillis();
            HashMap<String,String> glassIds=new HashMap<>();
            productHisList.forEach(e->glassIds.put(e.getGlass_id_o(),e.getGlass_id_o()));
            //ext表
            HashMap<String,WppShtOpeHisExt> wppExtList=loadOpeHisInfoService.getExtInfoList(glassIds);
            long endTime = System.currentTimeMillis();
            long time=endTime-startTime;
            logger.warn("查询ext花费的总的时间：{}",time);


            for (ProductHis productHis : productHisList) {
                try {
                    if (productHis.getProd_id().contains("DUMMY")) {
                        logger.warn("glassId={} opeId={} linkkey={} prodId 包含 DUMMY，跳过", productHis.getGlass_id_o(), productHis.getOpe_id(), productHis.getLinkkey());
                        continue;
                    }
                    if (!"A".equals(productHis.getGlass_id_o().substring(0,1)) && !"C".equals(productHis.getGlass_id_o().substring(0,1))) {
                        logger.warn("glassId={} opeId={} linkkey={} glassId 信息不符合要求，跳过", productHis.getGlass_id_o(), productHis.getOpe_id(), productHis.getLinkkey());
                        continue;
                    }
                    if (ProcessUtil.opeLimit(productHis.getOpe_id())) {
                        logger.warn("glassId={} opeId={} linkkey={} opeId 信息不符合要求，跳过", productHis.getGlass_id_o(), productHis.getOpe_id(), productHis.getLinkkey());
                        continue;
                    }
//                    startTime = System.currentTimeMillis();
                    if("A1200".equals(productHis.getOpe_id())){
                        //找A1100的traceOut
                        ProductHis productHisA1100=loadOpeHisInfoService.getA1100TrackOut(productHis.getVirtualglassname(),productHis.getGlass_id_o());
                        //处理A1100
                        if(null!=productHisA1100) {
                            WppShtOpeHisExt wppExtA1100 = loadOpeHisInfoService.getExtInfo(productHisA1100.getGlass_id_o());
                            saveASht(productHisA1100, prodMap, opeMap, wppExtA1100, etlConfD.getEtlTimestamp(), shopStartTime);
                            logger.info("glassId={} opeId={} lgofTimestamp={} linkkey={} 保存成功。",
                                    productHisA1100.getGlass_id_o(), productHisA1100.getOpe_id(), productHisA1100.getLogof_timestamp(), productHisA1100.getLinkkey());
                            loadOpeHisInfoService.clearObject(wppExtA1100);
                        }
                    }



                    if ("A".equalsIgnoreCase(productHis.getShop_id().substring(0, 1))) {
                        saveASht(productHis, prodMap, opeMap, wppExtList.get(productHis.getGlass_id_o()), etlConfD.getEtlTimestamp(),shopStartTime);
                    } else if ("O".equalsIgnoreCase(productHis.getShop_id().substring(0, 1))) {
                        saveCSht(productHis, prodMap, opeMap, wppExtList.get(productHis.getGlass_id_o()), etlConfD.getEtlTimestamp(),shopStartTime);
                    } else if ("C".equalsIgnoreCase(productHis.getShop_id().substring(0, 1))) {
                        saveFSht(productHis, prodMap, opeMap, wppExtList.get(productHis.getGlass_id_o()), etlConfD.getEtlTimestamp(),shopStartTime);
                    }
//                    endTime = System.currentTimeMillis();
//                    time=endTime-startTime;
//                    logger.warn("该片{} 保存的时间：{}",productHis.getGlass_id_o(),time);
                    logger.info("glassId={} opeId={} lgofTimestamp={} linkkey={} 保存成功。",
                            productHis.getGlass_id_o(), productHis.getOpe_id(),productHis.getLogof_timestamp(),productHis.getLinkkey());
                    loadOpeHisInfoService.clearObject(wppExtList.get(productHis.getGlass_id_o()));
                    okCnt++;

                } catch (ETLException2 e) {
                    String err = e.getErrorCode().getErrorMsg() + "错误原因：" + e.getErrMsg();
                    logger.error("glassId={} opeId={} linkkey={} {},错误原因：{}",
                            productHis.getGlass_id_o(), productHis.getOpe_id(), productHis.getLinkkey(), e.getErrorCode().getErrorMsg(), LoggerUtil.stackTraceToString(e));
                    if (StringUtils.isEmpty(err)) {
                        errMsg = "glassId=" + productHis.getGlass_id_o() + " opeId=" + productHis.getOpe_id() + " linkkey=" + productHis.getLinkkey() + " " + err + "\n";
                    } else {
                        errMsg += "glassId=" + productHis.getGlass_id_o() + " opeId=" + productHis.getOpe_id() + " linkkey=" + productHis.getLinkkey() + " " + err + "\n";

                    }
                    errCnt++;
                } catch (Exception e) {
                    String err = LoggerUtil.stackTraceToString(e);
                    logger.error("glassId={} opeId={} linkkey={} 保存错误，错误原因：{}",
                            productHis.getGlass_id_o(), productHis.getOpe_id(), productHis.getLinkkey(), err);
                    if (StringUtils.isEmpty(err)) {
                        errMsg = "glassId=" + productHis.getGlass_id_o() + " opeId=" + productHis.getOpe_id() + " linkkey=" + productHis.getLinkkey() + " " + err + "\n";
                    } else {
                        errMsg += "glassId=" + productHis.getGlass_id_o() + " opeId=" + productHis.getOpe_id() + " linkkey=" + productHis.getLinkkey() + " " + err + "\n";

                    }
                    errCnt++;
                }

            }
        }else{
            logger.info("没有此区间的数据。"); // todo print log & save etl data
        }
        resMsg[0] = String.valueOf(okCnt);
        resMsg[1] = String.valueOf(errCnt);
        resMsg[2] = errMsg;

        return resMsg;
    }


    public void saveASht(ProductHis prodHis, HashMap<String, Integer> prodMap, HashMap<String, Integer> opeMap, WppShtOpeHisExt wppExt, Timestamp etlTimestamp, HashMap<String, ProductHis> shopStartTime) throws Exception {
        String shop_id = prodHis.getShop_id();
        String glass_id_o = prodHis.getGlass_id_o();
        String ope_id = prodHis.getOpe_id();
        String eqpt_id = prodHis.getEqpt_id();
        String linkkey = prodHis.getLinkkey();
        String prod_id = prodHis.getProd_id();
        Timestamp logon_timestamp = null;
        String ng_mark = "";
        String glass_judge_ary = "";
        String glass_grade_ary = "";
        String tft_pnl_grade = "";
        Timestamp tft_start_timestamp = null;
        Timestamp tft_shipping_timestamp = null;

        //根据TrackOut查询TrackIn,ship,
        List<ProductHis> ashtHis=new ArrayList<>();
//        long startTime1 = System.currentTimeMillis();
        if("A1100".equals(prodHis.getOpe_id())){
            ashtHis=loadOpeHisInfoService.getAshtTrackIn(shop_id, ope_id, glass_id_o, linkkey,prodHis.getVirtualglassname());
        }else {
            ashtHis = loadOpeHisInfoService.getAshtTrackIn(shop_id, ope_id, glass_id_o, linkkey,null);
        }
//        long endTime1 = System.currentTimeMillis();
//        long time1=endTime1-startTime1;
//        logger.warn("该片{} 查询trackin的时间：{}",glass_id_o,time1);
//        startTime1 = System.currentTimeMillis();
        if (!ashtHis.isEmpty()) {
            logon_timestamp = ashtHis.get(0).getLogon_timestamp();
            ng_mark = ProcessUtil.getStringS(ashtHis.get(0).getNg_mark());
            glass_judge_ary = ProcessUtil.getStringS(ashtHis.get(0).getGlass_judge_ary());
            glass_grade_ary = ProcessUtil.getStringS(ashtHis.get(0).getGlass_grade_ary());
            tft_pnl_grade = ProcessUtil.getStringS(ashtHis.get(0).getTft_pnl_grade());
            if(!shopStartTime.isEmpty()&&null!=shopStartTime.get(glass_id_o+"_"+ope_id)) tft_start_timestamp = ProcessUtil.getTimestamp(shopStartTime.get(glass_id_o+"_"+ope_id).getTft_start_timestamp());
            tft_shipping_timestamp = ProcessUtil.getTimestamp(ashtHis.get(0).getTft_shipping_timestamp());
        }

        Integer prodKey = prodMap.get(prod_id + "@" + shop_id);
//        if (prodKey == null) {
//            List<MProdD> mProdDS = loadOpeHisInfoService.getMProdDS(prod_id, shop_id);
//            if (mProdDS != null && mProdDS.size() > 0) {
//                MProdD mProdD = mProdDS.get(0);
//                prodKey = mProdD.getProdKey();
//            }
//        }
        Integer opeKey = opeMap.get(ope_id + "@" + shop_id);
//        if (opeKey == null) {
//            List<MOpeD> mOpeDS = loadOpeHisInfoService.getMOpeDS(ope_id, shop_id);
//            if (mOpeDS != null && mOpeDS.size() > 0) {
//                MOpeD mOpeD = mOpeDS.get(0);
//                opeKey = mOpeD.getOpeKey();
//            }
//        }


        WppAshtOpeHis wppAshtOpe = new WppAshtOpeHis();
        if (prodKey != null) {
            wppAshtOpe.setProdKeyFk(prodKey);
        }
        if (opeKey != null) {
            wppAshtOpe.setOpeKeyFk(opeKey);
        }
        wppAshtOpe.setGlassId(glass_id_o);
        wppAshtOpe.setProdId(prod_id);
        wppAshtOpe.setOwner(prodHis.getOwner());
        wppAshtOpe.setLotId(prodHis.getLot_id());
        wppAshtOpe.setGrade(prodHis.getGrade());
        wppAshtOpe.setOpeId(ope_id);
        wppAshtOpe.setLogonTimestamp(logon_timestamp);
        wppAshtOpe.setLogofTimestamp(prodHis.getLogof_timestamp());
        wppAshtOpe.setEvtUser(prodHis.getEvt_user());
        wppAshtOpe.setEqptId(eqpt_id);
        wppAshtOpe.setUnitEq(prodHis.getUnit_eq());
        wppAshtOpe.setRecipeId(prodHis.getRecipe_id());
        wppAshtOpe.setPosition(prodHis.getPosition());
        wppAshtOpe.setProductSpecversion(prodHis.getProduct_specversion());
        wppAshtOpe.setCarrierName(prodHis.getCarrier_name());
        wppAshtOpe.setReworkCount(prodHis.getRework_count());
        wppAshtOpe.setEtlTimestamp(etlTimestamp);
        wppAshtOpe.setEtlEventNode(InetAddress.getLocalHost().getHostAddress());
        wppAshtOpe.setMesTimestamp(prodHis.getMes_timestamp());
        wppAshtOpe.setEtlEventName(InetAddress.getLocalHost().getHostName());
        wppAshtOpe.setMaskId(prodHis.getMask_id());
//            prodHis.setNg_mark(prodHis.getNg_mark());
        wppAshtOpe.setAbnormalFlag1(prodHis.getAbnormal_flag_1());
        wppAshtOpe.setOwnertype(prodHis.getOwnertype());
        wppAshtOpe.setProductiontype(prodHis.getProductiontype());
        wppAshtOpe.setNgMark(ng_mark);
        wppAshtOpe.setOpeTblName("wpp_asht_ope_his");


        if (!StringUtils.isEmpty(glass_judge_ary)) {
            wppExt.setGlassJudgeAry(glass_judge_ary);
        }
        if (!StringUtils.isEmpty(glass_grade_ary)) {
            wppExt.setGlassGradeAry(glass_grade_ary);
        }
        if (!StringUtils.isEmpty(tft_pnl_grade)) {
            wppExt.setTftPnlGrade(tft_pnl_grade);
        }
        if (null != tft_start_timestamp) {
            wppExt.setTftStartTimestamp(tft_start_timestamp);
        }
        if (null != tft_shipping_timestamp) {
            wppExt.setTftShippingTimestamp(tft_shipping_timestamp);
        }
        wppExt.setThickness(ProcessUtil.getBigDecimal(prodHis.getThickness()));
        wppExt.setEtlTimestamp(etlTimestamp);
        wppExt.setOpeTblName("wpp_sht_ope_his_ext");

        Timestamp trackOutTimestamp = wppAshtOpe.getLogofTimestamp();

        final LocalDateTime localDateTime = trackOutTimestamp.toLocalDateTime();
        LocalDate localDate = LocalDate.ofYearDay(localDateTime.getYear(), localDateTime.getDayOfYear());

//            if (StringUtils.equalsIgnoreCase(shfName, "Night")) {
        if (localDateTime.getHour() < 8 || (localDateTime.getHour() == 8 && localDateTime.getMinute() < 30)) {
            localDate = localDate.plusDays(-1);
        }
//            }
        wppAshtOpe.setCaldDate(java.sql.Date.valueOf(localDate));
        String[] res = getCaltDate(trackOutTimestamp);
        wppAshtOpe.setHourKeyFk(Integer.valueOf(res[0]));
        if ("Day".equals(res[1])) {
            wppAshtOpe.setShfId("10AD");
        } else {
            wppAshtOpe.setShfId("10AN");
        }
//        endTime1 = System.currentTimeMillis();
//        time1=endTime1-startTime1;
//        logger.warn("该片{} process的时间：{}",glass_id_o,time1);

//        startTime1 = System.currentTimeMillis();
        try {
            //FIXME:测试用，不能送出消息给RabbitMQ
            rabbitTemplate.convertAndSend("qmsExchange", "wpp_asht_ope_his", JacksonUtil.toJSONStr(wppAshtOpe));
            rabbitTemplate.convertAndSend("qmsExchange", "wpp_sht_ope_his_ext", JacksonUtil.toJSONStr(wppExt));
        } catch (Exception e) {
            throw new ETLException2(ErrorCode.ERROR_RABBITMQ_OPEHIS_ASHT, e);
        }
//        endTime1 = System.currentTimeMillis();
//        time1=endTime1-startTime1;
//        logger.warn("该片{} MQ的时间：{}",glass_id_o,time1);


    }



    public void saveFSht(ProductHis prodHis, HashMap<String, Integer> prodMap, HashMap<String, Integer> opeMap, WppShtOpeHisExt wppExt, Timestamp etlTimestamp, HashMap<String, ProductHis> shopStartTime) throws Exception {
        String shop_id = prodHis.getShop_id();
        String glass_id_o = prodHis.getGlass_id_o();
        String ope_id = prodHis.getOpe_id();
        String eqpt_id = prodHis.getEqpt_id();
        Integer rework_count = prodHis.getRework_count();
        String linkkey = prodHis.getLinkkey();
        String prod_id = prodHis.getProd_id();
        Timestamp logon_timestamp = null;
        String ng_mark = "";
        String glass_judge_cf = "";
        String glass_grade_cf = "";
        String cf_pnl_grade = "";
        Timestamp cf_start_timestamp = null;
        Timestamp cf_shipping_timestamp = null;
        //根据TrackOut查询TrackIn
        List<ProductHis> fshtHis = loadOpeHisInfoService.getFshtTrackIn(shop_id, ope_id, glass_id_o, linkkey);

            if (!fshtHis.isEmpty()) {
                logon_timestamp = fshtHis.get(0).getLogon_timestamp();
                ng_mark = ProcessUtil.getStringS(fshtHis.get(0).getNg_mark());
                glass_judge_cf = ProcessUtil.getStringS(fshtHis.get(0).getGlass_judge_cf());
                glass_grade_cf = ProcessUtil.getStringS(fshtHis.get(0).getGlass_grade_cf());
                cf_pnl_grade = ProcessUtil.getStringS(fshtHis.get(0).getCf_pnl_grade());
                if(!shopStartTime.isEmpty()&&null!=shopStartTime.get(glass_id_o+"_"+ope_id)) cf_start_timestamp = ProcessUtil.getTimestamp(shopStartTime.get(glass_id_o+"_"+ope_id).getCf_start_timestamp());
                cf_shipping_timestamp = ProcessUtil.getTimestamp(fshtHis.get(0).getCf_shipping_timestamp());
            }


        Integer prodKey = prodMap.get(prod_id + "@" + shop_id);
//        if (prodKey == null) {
//            List<MProdD> mProdDS = loadOpeHisInfoService.getMProdDS(prod_id, shop_id);
//            if (mProdDS != null && mProdDS.size() > 0) {
//                MProdD mProdD = mProdDS.get(0);
//                prodKey = mProdD.getProdKey();
//            }
//        }
        Integer opeKey = opeMap.get(ope_id + "@" + shop_id);
//        if (opeKey == null) {
//            List<MOpeD> mOpeDS = loadOpeHisInfoService.getMOpeDS(ope_id, shop_id);
//            if (mOpeDS != null && mOpeDS.size() > 0) {
//                MOpeD mOpeD = mOpeDS.get(0);
//                opeKey = mOpeD.getOpeKey();
//            }
//        }

            WppFshtOpeHis wppFshtOpe = new WppFshtOpeHis();
            if (prodKey != null) {
                wppFshtOpe.setProdKeyFk(prodKey);
            }
            if (opeKey != null) {
                wppFshtOpe.setOpeKeyFk(opeKey);
            }
            wppFshtOpe.setGlassId(glass_id_o);
            wppFshtOpe.setProdId(prod_id);
            wppFshtOpe.setOwner(prodHis.getOwner());
            wppFshtOpe.setLotId(prodHis.getLot_id());
            wppFshtOpe.setGrade(prodHis.getGrade());
            wppFshtOpe.setOpeId(ope_id);
            wppFshtOpe.setLogonTimestamp(logon_timestamp);
            wppFshtOpe.setLogofTimestamp(prodHis.getLogof_timestamp());
            wppFshtOpe.setEvtUser(prodHis.getEvt_user());
            wppFshtOpe.setEqptId(eqpt_id);
            wppFshtOpe.setUnitEq(prodHis.getUnit_eq());
            wppFshtOpe.setRecipeId(prodHis.getRecipe_id());
            wppFshtOpe.setPosition(prodHis.getPosition());
            wppFshtOpe.setProductSpecversion(prodHis.getProduct_specversion());
            wppFshtOpe.setCarrierName(prodHis.getCarrier_name());
            wppFshtOpe.setPosition(prodHis.getPosition());
            wppFshtOpe.setProductSpecversion(prodHis.getProduct_specversion());
            wppFshtOpe.setReworkCount(prodHis.getRework_count());
            wppFshtOpe.setEtlTimestamp(etlTimestamp);
            wppFshtOpe.setEtlEventNode(InetAddress.getLocalHost().getHostAddress());
            wppFshtOpe.setMesTimestamp(prodHis.getMes_timestamp());
            wppFshtOpe.setEtlEventName(InetAddress.getLocalHost().getHostName());
//            wppFshtOpe.setNg_mark(prodHis.getNg_mark());
            wppFshtOpe.setAbnormalFlag1(prodHis.getAbnormal_flag_1());
            wppFshtOpe.setOwnertype(prodHis.getOwnertype());
            wppFshtOpe.setProductiontype(prodHis.getOwnertype());
            wppFshtOpe.setNgMark(ng_mark);
            wppFshtOpe.setOpeTblName("wpp_fsht_ope_his");


            if (!StringUtils.isEmpty(glass_judge_cf)) {
                wppExt.setGlassJudgeCf(glass_judge_cf);
            }
            if (!StringUtils.isEmpty(glass_grade_cf)) {
                wppExt.setGlassGradeCf(glass_grade_cf);
            }
            if (!StringUtils.isEmpty(cf_pnl_grade)) {
                wppExt.setCfPnlGrade(cf_pnl_grade);
            }
            if (null != cf_start_timestamp) {
                wppExt.setCfStartTimestamp(cf_start_timestamp);
            }
            if (null != cf_shipping_timestamp) {
                wppExt.setCfShippingTimestamp(cf_shipping_timestamp);
            }
            wppExt.setThickness(ProcessUtil.getBigDecimal(prodHis.getThickness()));
            wppExt.setEtlTimestamp(etlTimestamp);
            wppExt.setOpeTblName("wpp_sht_ope_his_ext");

            Timestamp trackOutTimestamp = wppFshtOpe.getLogofTimestamp();
            final LocalDateTime localDateTime = trackOutTimestamp.toLocalDateTime();
            LocalDate localDate = LocalDate.ofYearDay(localDateTime.getYear(), localDateTime.getDayOfYear());

            if (localDateTime.getHour() < 8 || (localDateTime.getHour() == 8 && localDateTime.getMinute() < 30)) {
                localDate = localDate.plusDays(-1);
            }
            wppFshtOpe.setCaldDate(java.sql.Date.valueOf(localDate));
            String[] res = getCaltDate(trackOutTimestamp);
            wppFshtOpe.setHourKeyFk(Integer.valueOf(res[0]));
            if ("Day".equals(res[1])) {
                wppFshtOpe.setShfId("10CD");
            } else {
                wppFshtOpe.setShfId("10CN");
            }
            try {
                rabbitTemplate.convertAndSend("qmsExchange", "wpp_fsht_ope_his", JacksonUtil.toJSONStr(wppFshtOpe));
                rabbitTemplate.convertAndSend("qmsExchange", "wpp_sht_ope_his_ext", JacksonUtil.toJSONStr(wppExt));
            } catch (Exception e) {
                throw new ETLException2(ErrorCode.ERROR_RABBITMQ_OPEHIS_FSHT, e);
            }

    }

    public void saveCSht(ProductHis prodHis, HashMap<String, Integer> prodMap, HashMap<String, Integer> opeMap, WppShtOpeHisExt wppExt, Timestamp etlTimestamp, HashMap<String, ProductHis> shopStartTime) throws Exception {
        String shop_id = prodHis.getShop_id();
        String glass_id_o = prodHis.getGlass_id_o();
        String ope_id = prodHis.getOpe_id();
        String eqpt_id = prodHis.getEqpt_id();
        Integer rework_count = prodHis.getRework_count();
        String linkkey = prodHis.getLinkkey();
        String prod_id = prodHis.getProd_id();
        Timestamp logon_timestamp = null;
        String ng_mark = "";
        String product_id_rep = "";
        String workorder_id = "";
        String workorder_id_rtp = "";
        Timestamp oc_start_timestamp = null;
        Timestamp oc1_bank_in_timestamp = null;
        Timestamp oc2_start_timestamp = null;
        Timestamp oc_shipping_timestamp = null;
        String oc_pnl_losscode_ct1 = prodHis.getOc_pnl_losscode_ct1();
        String oc_pnl_lossCode_c_insp = prodHis.getOc_pnl_losscode_c_insp();

        //根据TrackOut查询TrackIn
        List<ProductHis> cshtHis = loadOpeHisInfoService.getCshtTrackIn(shop_id, ope_id, glass_id_o, linkkey);
            if (!cshtHis.isEmpty()) {
                logon_timestamp = cshtHis.get(0).getLogon_timestamp();
                ng_mark = ProcessUtil.getStringS(cshtHis.get(0).getNg_mark());
                product_id_rep = ProcessUtil.getStringS(cshtHis.get(0).getProduct_id_erp());
                workorder_id = ProcessUtil.getStringS(cshtHis.get(0).getWorkorder_id());
                workorder_id_rtp = ProcessUtil.getStringS(cshtHis.get(0).getWorkorder_id_rtp());
                oc_start_timestamp = ProcessUtil.getTimestamp(cshtHis.get(0).getOc_start_timestamp());
                oc1_bank_in_timestamp = ProcessUtil.getTimestamp(cshtHis.get(0).getOc1_bank_in_timestamp());
                if(!shopStartTime.isEmpty()&&null!=shopStartTime.get(glass_id_o+"_"+ope_id)) oc2_start_timestamp = ProcessUtil.getTimestamp(shopStartTime.get(glass_id_o+"_"+ope_id).getOc2_start_timestamp());
                oc_shipping_timestamp = ProcessUtil.getTimestamp(cshtHis.get(0).getOc_shipping_timestamp());
            }


        Integer prodKey = prodMap.get(prod_id + "@" + shop_id);
//        if (prodKey == null) {
//            List<MProdD> mProdDS = loadOpeHisInfoService.getMProdDS(prod_id, shop_id);
//            if (mProdDS != null && mProdDS.size() > 0) {
//                MProdD mProdD = mProdDS.get(0);
//                prodKey = mProdD.getProdKey();
//            }
//        }
        Integer opeKey = opeMap.get(ope_id + "@" + shop_id);
//        if (opeKey == null) {
//            List<MOpeD> mOpeDS = loadOpeHisInfoService.getMOpeDS(ope_id, shop_id);
//            if (mOpeDS != null && mOpeDS.size() > 0) {
//                MOpeD mOpeD = mOpeDS.get(0);
//                opeKey = mOpeD.getOpeKey();
//            }
//        }
            WppCshtOpeHis wppCshtOpe = new WppCshtOpeHis();
            if (prodKey != null) {
                wppCshtOpe.setProdKeyFk(prodKey);
            }
            if (opeKey != null) {
                wppCshtOpe.setOpeKeyFk(opeKey);
            }
            // wppCshtOpe.setRealFlg("Y");

            wppCshtOpe.setGlassId(glass_id_o);
            wppCshtOpe.setProdId(prod_id);
            wppCshtOpe.setOwner(prodHis.getOwner());
            wppCshtOpe.setGrade(prodHis.getGrade());
            wppCshtOpe.setOpeId(ope_id);
            wppCshtOpe.setLotId(prodHis.getLot_id());
            wppCshtOpe.setCfGlassId(prodHis.getCf_glass_id());
            wppCshtOpe.setTftGlassId(prodHis.getTft_glass_id());
            wppCshtOpe.setLogonTimestamp(logon_timestamp);
            wppCshtOpe.setLogofTimestamp(prodHis.getLogof_timestamp());
            wppCshtOpe.setEvtUser(prodHis.getEvt_user());
            wppCshtOpe.setEqptId(eqpt_id);
            wppCshtOpe.setUnitEq(prodHis.getUnit_eq());
            wppCshtOpe.setRecipeId(prodHis.getRecipe_id());
            wppCshtOpe.setCarrierName(prodHis.getCarrier_name());
            wppCshtOpe.setPosition(prodHis.getPosition());
            wppCshtOpe.setProductSpecversion(prodHis.getProduct_specversion());
            wppCshtOpe.setReworkCount(prodHis.getRework_count());
            wppCshtOpe.setEtlTimestamp(etlTimestamp);
            wppCshtOpe.setEtlEventNode(InetAddress.getLocalHost().getHostAddress());
            wppCshtOpe.setMesTimestamp(prodHis.getMes_timestamp());
            wppCshtOpe.setEtlEventName(InetAddress.getLocalHost().getHostName());
            wppCshtOpe.setOwnertype(prodHis.getOwnertype());
            wppCshtOpe.setProductiontype(prodHis.getProductiontype());
            wppCshtOpe.setNgmark(ng_mark);
            wppCshtOpe.setOpeTblName("wpp_csht_ope_his");


            if (!StringUtils.isEmpty(product_id_rep)) {
                wppExt.setProductIdErp(product_id_rep);
            }
            if (!StringUtils.isEmpty(workorder_id)) {
                wppExt.setWorkorderId(workorder_id);
            }
            if (!StringUtils.isEmpty(workorder_id_rtp)) {
                wppExt.setWorkorderIdRtp(workorder_id_rtp);
            }
            if (null != oc_start_timestamp) {
                wppExt.setOcStartTimestamp(oc_start_timestamp);
            }
            if (null != oc1_bank_in_timestamp) {
                wppExt.setOc1BankInTimestamp(oc1_bank_in_timestamp);
            }
            if (null != oc2_start_timestamp) {
                wppExt.setOc2StartTimestamp(oc2_start_timestamp);
            }
            if (null != oc_shipping_timestamp) {
                wppExt.setOcShippingTimestamp(oc_shipping_timestamp);
            }
            if (null != oc_pnl_losscode_ct1) {
                wppExt.setOcPnlLosscodeCt1(oc_pnl_losscode_ct1);
            }
            if (null != oc_pnl_lossCode_c_insp) {
                wppExt.setOcPnlLosscodeCInsp(oc_pnl_lossCode_c_insp);
            }
            wppExt.setThickness(ProcessUtil.getBigDecimal(prodHis.getThickness()));
            wppExt.setEtlTimestamp(etlTimestamp);
            wppExt.setOpeTblName("wpp_sht_ope_his_ext");
            //modify by LynnSea

            Timestamp trackOutTimestamp = wppCshtOpe.getLogofTimestamp();


            //判断日期归属，白班和夜班存的是同一天

            final LocalDateTime localDateTime = trackOutTimestamp.toLocalDateTime();
            LocalDate localDate = LocalDate.ofYearDay(localDateTime.getYear(), localDateTime.getDayOfYear());

            if (localDateTime.getHour() < 8 || (localDateTime.getHour() == 8 && localDateTime.getMinute() < 30)) {
                localDate = localDate.plusDays(-1);
            }
            wppCshtOpe.setCaldDate(java.sql.Date.valueOf(localDate));
            String[] res = getCaltDate(trackOutTimestamp);
            wppCshtOpe.setHourKeyFk(Integer.valueOf(res[0]));
            if ("Day".equals(res[1])) {
                wppCshtOpe.setShfId("10OD");
            } else {
                wppCshtOpe.setShfId("10ON");
            }

            try {
                rabbitTemplate.convertAndSend("qmsExchange", "wpp_csht_ope_his", JacksonUtil.toJSONStr(wppCshtOpe));
                rabbitTemplate.convertAndSend("qmsExchange", "wpp_sht_ope_his_ext", JacksonUtil.toJSONStr(wppExt));
            } catch (Exception e) {
                throw new ETLException2(ErrorCode.ERROR_RABBITMQ_OPEHIS_CSHT, e);
            }
    }

    private String[] getCaltDate(Timestamp lgof_time) {
        String[] res = new String[2];
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(lgof_time.getTime());
        String hour = date.substring(8, 14);
        int hourint = Integer.parseInt(hour);
        if (hourint >= 3000 && hourint < 13000) res[0] = "1";
        else if (hourint >= 13000 && hourint < 23000) res[0] = "2";
        else if (hourint >= 23000 && hourint < 33000) res[0] = "3";
        else if (hourint >= 33000 && hourint < 43000) res[0] = "4";
        else if (hourint >= 43000 && hourint < 53000) res[0] = "5";
        else if (hourint >= 53000 && hourint < 63000) res[0] = "6";
        else if (hourint >= 63000 && hourint < 73000) res[0] = "7";
        else if (hourint >= 73000 && hourint < 83000) res[0] = "8";
        else if (hourint >= 83000 && hourint < 93000) res[0] = "9";
        else if (hourint >= 93000 && hourint < 103000) res[0] = "10";
        else if (hourint >= 103000 && hourint < 113000) res[0] = "11";
        else if (hourint >= 113000 && hourint < 123000) res[0] = "12";
        else if (hourint >= 123000 && hourint < 133000) res[0] = "13";
        else if (hourint >= 133000 && hourint < 143000) res[0] = "14";
        else if (hourint >= 143000 && hourint < 153000) res[0] = "15";
        else if (hourint >= 153000 && hourint < 163000) res[0] = "16";
        else if (hourint >= 163000 && hourint < 173000) res[0] = "17";
        else if (hourint >= 173000 && hourint < 183000) res[0] = "18";
        else if (hourint >= 183000 && hourint < 193000) res[0] = "19";
        else if (hourint >= 193000 && hourint < 203000) res[0] = "20";
        else if (hourint >= 203000 && hourint < 213000) res[0] = "21";
        else if (hourint >= 213000 && hourint < 223000) res[0] = "22";
        else if (hourint >= 223000 && hourint < 233000) res[0] = "23";
        else if (hourint >= 233000 || hourint < 3000) res[0] = "24";

        if (Integer.valueOf(res[0]) >= 8 && Integer.valueOf(res[0]) <= 20) {
            res[1] = "Day";
        } else {
            res[1] = "Night";
        }

        return res;
    }
}
